package net.dotool.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import net.dotool.ConnectionTools;

/**
 * 
 * @author 李岩飞
 * @email eliyanfei@126.com	
 * 2017年10月27日 下午5:04:16
 *
 */
public class ADatabaseWriter {
	private Connection conn = null;
	private PreparedStatement ps = null;
	private int count = 1;

	/**
	 * @param conn 数据库连接
	 * @param table 数据库表名
	 */
	public ADatabaseWriter(Connection conn, String tableName) {
		try {
			this.conn = conn;
			this.ps = conn.prepareStatement(ConnectionTools.getInsertSql(tableName, conn));
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 释放资源
	 */
	public void release() {
		try {
			ps.executeBatch();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionTools.closeAll(null, ps, conn);
		}
	}

	/**
	 * 写数据
	 */
	public void write(Object... params) {
		try {
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					ps.setObject(i + 1, params[i]);
				}
				ps.addBatch();
				if (count++ % 2000 == 0) {
					ps.executeBatch();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
